/**
 * 转换字符串，输出 10 位时间戳
 * @return {str} timestamp 时间戳
 */
function gmt(str) {
  let date = str ? new Date(str) : new Date();
  return parseInt(date.getTime() / 1000).toString();
};

/**
 * 转换 16 进制 rgb 为 10 进制数字输出
 * @return {arr[int]} res 颜色值
 */
function rgb(str) {
  let res = [0, 0, 0], i = -1;
  if (str[0] == '#') str = str.substring(1)
  if (str[6]) 
    console.error('字符串不对');
  else for (; i++ < 2;) 
    res[i] = parseInt(str.substr(2 * i, 2), 16);
  return res;
};

/**
 * 封装 formatTime
 * @param  {int} timestamp 时间戳
 * 
 * @param  {dt}  date      时间
 * @param  {str} type      格式化类型
 * @return {str} formatted date & time
 */
function formatTime(date, type) {
  var year = date.getFullYear(),
    month = formatNumber(date.getMonth() + 1),
    day = formatNumber(date.getDate()),
    hours = formatNumber(date.getHours()),
    minute = formatNumber(date.getMinutes()),
    second = formatNumber(date.getSeconds());
  switch (type) {
    case 'cn':
      return year + '年' + month + '月' + day + '日 ' +
        hours + '时' + minute + '分' + second + '秒';
    case 'd-t':
      return ([year, month, day]).join('-') + ' ' +
        ([hours, minute, second]).join(':');
    case 'd/t':
      return ([year, month, day]).join('/') + ' ' +
        ([hours, minute, second]).join(':');
    case '-':
      return ([year, month, day]).join('-');
    case '/':
      return ([year, month, day]).join('/');
  }
  return ([hours, minute, second]).join(':');
}
const formatNumber = n => {
  n = n.toString(); return n[1] ? n : '0' + n;
}

function random(n) {
  const wordList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2',
  '3', '4', '5', '6', '7', '8', '9', '0']
  var result = ''
  for (let i=0; i<n; i++){
    result += wordList[Math.round(Math.random() * 36)]
  }
  return result
}

function encapsulate() {
  wx.formatTime = formatTime;
  wx.gmt = gmt;
  wx.rgb = rgb;
  wx.random = random;
}

module.exports = {
  encapsulate: encapsulate
}
